package tool

import (
	"bytes"
	"encoding/gob"
	"os"
)

// 保存数据到二进制文件
func SaveToBinary(data EncryptedData, filename string) error {
	file, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		return err
	}
	defer file.Close()

	var buffer bytes.Buffer
	encoder := gob.NewEncoder(&buffer)
	err = encoder.Encode(data)
	if err != nil {
		return err
	}

	_, err = file.Write(buffer.Bytes())
	return err
}

// 读取二进制文件
func LoadFromBinary(filename string) ([]EncryptedData, error) {
	file, err := os.Open(filename)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	var data []EncryptedData
	decoder := gob.NewDecoder(file)

	for {
		var record EncryptedData
		err := decoder.Decode(&record)
		if err != nil {
			break
		}
		data = append(data, record)
	}
	return data, nil
}
